<template>
  <div class="register">
    <el-form ref="registerRef" :model="register" :rules="rules">
      <el-form-item prop="username">
        <el-input v-model="register.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item prop="email">
        <el-input v-model="register.email" placeholder="电子邮箱" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="register.password" type="password" placeholder="密码" />
      </el-form-item>
      <el-button type="primary" class="register-btn" @click="registerFn">注册</el-button>
    </el-form>
  </div>
</template>

<script>
import { register } from '@/api/user'
// 验证规则
const rules = {
  username: [
    { required: true, trigger: 'blur', message: '请输入用户名' },
    { min: 6, max: 15, trigger: 'blur', message: '用户名6-15位' }
  ],
  email: [
    { required: true, trigger: 'blur', message: '请输入电子邮箱' },
    { pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/, trigger: 'blur', message: '请输入正确格式邮箱' }
  ],
  password: [
    { required: true, trigger: 'blur', message: '请输入密码' },
    { min: 6, max: 15, trigger: 'blur', message: '密码长度6-15位' }
  ]
}
export default {
  data() {
    return {
      register: {
        username: '',
        email: '',
        password: ''
      },
      rules: rules
    }
  },
  methods: {
    // 注册
    registerFn() {
      // 判断是否验证通过
      this.$refs.registerRef.validate(async (verify) => {
        if (verify) {
          // 验证通过,发送请求注册
          try {
            await register(this.register)
            this.$message.success('注册成功')
          } catch (error) {
            // console.log(error.response.data.message[0].messages[0].message)
            this.$message.error(error.response.data.message[0].messages[0].message)
          }
          this.$refs.registerRef.resetFields()
          this.register = {
            username: '',
            email: '',
            password: ''
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.register-btn {
  width: 100%;
}
</style>
